package logic

import (
	"context"
	"encoding/json"
	"furniture/cache"
	"furniture/furniturerpc/furniturerpc"
	"furniture/furniturerpc/internal/svc"
	"furniture/models"
	"github.com/zeromicro/go-zero/core/logx"
	"time"
)

type ListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListLogic {
	return &ListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListLogic) List(in *furniturerpc.ListAddRequest) (*furniturerpc.ListResponse, error) {
	// todo: add your logic here and delete this line

	var furnData []models.Furn
	list := "list"

	key, _ := cache.Rdb.Get(cache.Ctx, list).Result()

	if key == "" {
		models.DB.Debug().Model(&models.Furniture{}).
			Select("furnitures.*, types.`name` as types_name,  brands.`name` as brand_name").
			Joins("LEFT JOIN types on furnitures.types_id = types.id").
			Joins("LEFT JOIN brands on furnitures.brand_id = brands.id").
			Find(&furnData)
		marshal, _ := json.Marshal(furnData)
		cache.Rdb.Set(cache.Ctx, list, marshal, time.Hour*1)
	} else {
		json.Unmarshal([]byte(key), &furnData)
	}

	var furnList []*furniturerpc.FurnList

	for _, datum := range furnData {
		f := furniturerpc.FurnList{
			Name:        datum.Name,
			Price:       float32(datum.Price),
			Address:     datum.Address,
			TypesName:   datum.TypesName,
			BrandName:   datum.BrandName,
			FurnitureId: int64(datum.ID),
		}
		furnList = append(furnList, &f)
	}

	return &furniturerpc.ListResponse{
		List: furnList,
	}, nil
}
